package com.awesome.javademo.threads.lock.reentrantlock;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import com.awesome.javademo.R;
import com.awesome.common.util.log.ShowLogUtil;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class ReentrantActivity extends AppCompatActivity {
    ReentrantLock lock = new ReentrantLock();
    Condition condition1 = lock.newCondition();
//    Condition condition2 = lock.newCondition();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reentrant);
        Thread thread1 = new Thread(() -> {
            ShowLogUtil.info("第一个线程开始执行");
            try {
                lock.lock();
                ShowLogUtil.info(" await start");
                condition1.await();
                ShowLogUtil.info(" await end");
//                for (int i = 65; i < 91; i++) {
//                    ShowLogUtil.info("----------thread1------- " + (char) i);
//                    condition2.signal();
//                    condition1.await();
//                }
//                condition2.signal();
            } catch (Exception e) {
            } finally {
                lock.unlock();
            }
            ShowLogUtil.info("第一个线程结束执行");
        });
        Thread thread2 = new Thread(() -> {
            ShowLogUtil.info("第二个线程开始执行");
            try {
                lock.lock();
//                for (int i = 0; i < 26; i++) {
//                    ShowLogUtil.info("----------thread2------- " + i);
//                    condition1.signal();
//                    condition2.await();
//                }
//                condition1.signal();
                ShowLogUtil.info(" notify start");
                condition1.notify();
                ShowLogUtil.info(" notify end");
            } catch (Exception e) {
            } finally {
                lock.unlock();
            }
            ShowLogUtil.info("第二个线程结束执行");
        });
        thread1.start();
        thread2.start();
    }
}